package com.itheima.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.store.Catalog;
import com.itheima.domain.store.Company;
import com.itheima.domain.store.Question;
import com.itheima.service.store.QuestionService;
import com.itheima.service.store.impl.QuestionServiceImpl;
import com.itheima.utils.BeanUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet(urlPatterns = "/store/question")
public class QuestionServlet extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 1.获取参数
        String operation = request.getParameter("operation");
        if ("list".equals(operation)) {
            this.list(request, response);
        } else if ("toAdd".equals(operation)) {
            this.toAdd(request, response);
        } else if ("save".equals(operation)) {
            this.save(request, response);
        } else if ("toEdit".equals(operation)) {
            this.toEdit(request, response);
        } else if ("edit".equals(operation)) {
            this.edit(request, response);
        } else if ("delete".equals(operation)) {
            this.delete(request, response);
        }else if ("toExamine".equals(operation)){
            this.toExamine(request,response);
        } else if ("downloadReport".equals(operation)) {
            try {
                this.downloadReport(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 跳转添加界面
    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询所有企业
        List<Company> companyList = companyService.findAll();
        request.setAttribute("companyList", companyList);
        // 查询所有类别
        List<Catalog> catalogList = catalogService.findAll();
        request.setAttribute("catalogList", catalogList);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/store/question/add.jsp").forward(request, response);
    }

    // 添加问题
    private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DiskFileItemFactory df = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(df);
        Question question = new Question();
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {
                    // 表单字段
                    if ("remark".equals(fileItem.getFieldName())) {
                        question.setRemark(fileItem.getString());
                    } else if ("subject".equals(fileItem.getFieldName())) {
                        question.setSubject(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("analysis".equals(fileItem.getFieldName())) {
                        question.setAnalysis(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("type".equals(fileItem.getFieldName())) {
                        question.setType(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("difficulty".equals(fileItem.getFieldName())) {
                        question.setDifficulty(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("isClassic".equals(fileItem.getFieldName())) {
                        question.setIsClassic(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("state".equals(fileItem.getFieldName())) {
                        question.setState(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("catalogId".equals(fileItem.getFieldName())) {
                        question.setCatalogId(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                        question.setCatalogName(question.getCatalogId() == "0" ? null : catalogService.findCatalogById(question.getCatalogId()).getCourseName());
                    } else if ("companyId".equals(fileItem.getFieldName())) {
                        question.setCompanyId(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                        question.setCompanyName(question.getCompanyId() == "0" ? null : companyService.findById(question.getCompanyId()).getName());
                    }
                } else {
                    // 上传的图片
                    String path = this.getServletContext().getRealPath("fileupload")  ;
                    String name = UUID.randomUUID().toString();
                    String suffix = fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
                    question.setPicture(path+"/"+name+suffix);
                    fileItem.write(new File(path,name+suffix));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // TODO: 2021/10/18 question看下是否有值

        question.setId(UUID.randomUUID().toString());
        System.out.println(question);
        questionService.addQuestion(question);
        // 返回查询
        list(request, response);
    }

    // 删除问题
    private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String id = request.getParameter("id");
        // 调用service
        QuestionService questionService=new QuestionServiceImpl();
        questionService.deleteQuestion(id);
        // 返回查询
        list(request, response);
    }


    // 调整修改界面
    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询要修改的findById
        String id = request.getParameter("id");
        Question question = questionService.findQuestionById(id);
        // 将数据加载到指定页面，让页面获取
        request.setAttribute("question",question);

        List<Company> companyList = companyService.findAll();
        List<Catalog> catalogList = catalogService.findAll();
        request.setAttribute("companyList",companyList);
        request.setAttribute("catalogList",catalogList);

        //  跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(request,response);
    }

    // 修改问题
    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        DiskFileItemFactory df = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(df);
        Question question = new Question();
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {
                    String aa  = new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8");

                    // 表单字段
                    if ("remark".equals(fileItem.getFieldName())) {
                        question.setRemark(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("id".equals(fileItem.getFieldName())) {
                        question.setId(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("subject".equals(fileItem.getFieldName())) {
                        question.setSubject(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("analysis".equals(fileItem.getFieldName())) {
                        question.setAnalysis(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("type".equals(fileItem.getFieldName())) {
                        question.setType(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("difficulty".equals(fileItem.getFieldName())) {
                        question.setDifficulty(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("isClassic".equals(fileItem.getFieldName())) {
                        question.setIsClassic(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("state".equals(fileItem.getFieldName())) {
                        question.setState(fileItem.getString());
                    }else if ("companyName".equals(fileItem.getFieldName())) {
                        question.setCompanyName(new String(fileItem.getString().getBytes(),"utf-8"));
                    }else if ("reviewStatus".equals(fileItem.getFieldName())){
                        question.setReviewStatus(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                    } else if ("catalogId".equals(fileItem.getFieldName())) {
                        question.setCatalogId(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                        question.setCatalogName(question.getCatalogId() == "0" ? null : catalogService.findCatalogById(question.getCatalogId()).getCourseName());
                    } else if ("companyId".equals(fileItem.getFieldName())) {
                        question.setCompanyId(new String(fileItem.getString().getBytes("iso-8859-1"),"utf-8"));
                        question.setCompanyName(question.getCompanyId() == "0" ? null : companyService.findById(question.getCompanyId()).getName());
                    }
                } else {
                    // 上传的图片
                    String path = this.getServletContext().getRealPath("fileupload");
                    String name = UUID.randomUUID().toString();
                    String suffix = fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
                    question.setPicture(path + "/" + name + suffix);
                    fileItem.write(new File(path, name + suffix));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // TODO: 2021/10/18 question看下是否有值

       // question.setId(UUID.randomUUID().toString());
        System.out.println(question);

        questionService.updateQuestion(question);
        // 返回查询
        list(request, response);

        //跳回页面list
        //response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
    }

    // 查询问题，分页查询
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageNum = request.getParameter("page");
        PageInfo page = questionService.findAll(pageNum);
        request.setAttribute("page", page);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/store/question/list.jsp").forward(request, response);
    }

    /**
     * 审核
     * 2021/10/18 19:58
     * created by yangyawen
     * @param request
     * @param response
     */
    private void toExamine(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        questionService.toExamine(id);

        // 返回查询
        list(request, response);



    }





    /**
     * 导入面面题目的数据文件下载
     * 2021/10/18 11:52
     * created by yangyawen
     */
    private void downloadReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 返回的数据类型为文件xlsx类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        // 设置下载的文件名
        String fileName = new String("面面题目.xlsx".getBytes(),"iso8859-1");
        response.addHeader("Content-Disposition","attachment;fileName="+fileName);
        // 生成报告的文件，然后传递到前端页面
        ByteArrayOutputStream os = questionService.getReport();
        // 获取产生响应的流对象
        ServletOutputStream sos = response.getOutputStream();
        // 将数据从原始的字节流对象中提取出来写入到servlet对应的输出流中
        os.writeTo(sos);
        // 将输出流刷新
        sos.flush();
        // 关流
        os.close();
    }
}
